<?php


namespace app\api\services;

use app\common\libs\Singleton;
use app\common\models\Member\MemberInfo;
use WeChat\Pay;
use WeMini\Crypt;

class WechatPayService
{
    use Singleton;

    protected $config = [
        'token' => 'aytdbrkbrd5pinn2jdawylbgugeajk2q',
        'appid' => 'wxff42c7f7d0e01741',//wxeaf630b2e02acfa9
        'appsecret' => 'e29e930a59631c85a30c825aa6e3a53f',//2d8f5c4b6dea7c7a2a0dfd1d6e595e27
        'encodingaeskey' => 'ejewWzQ2c1cS15qeQ8lxl35Z1c82J1LLbs5Z52S55qx',
        // 配置商户支付参数（可选，在使用支付功能时需要）
        'mch_id' => '1618568400',
        'mch_key' => 'AKb0SU3PGPW58gx66YPp9TtNGY6sTmFp',
        // 配置商户支付双向证书目录（可选，在使用退款|打款|红包时需要）
        'ssl_key' => '-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC1EhYfFief2rJt
jQf18VOc7I9zV/L8jsbI418i3jwLx3wSAd0+DWhW6Xd92fBPklnYoxyxcGGrXwSd
CYsKrYdXfPEEdjUZ1zkDWnHBjc/japfCgSXBzva+TCeSaXo2pRG6QUQDct7L3sS4
y6s88KSo8XYCIY70UDLs0/ur7ltfxg3wdm4C03pEAdIdyKHmLxY2B4Zhl5JJWsRm
5eDNgqtwCbh5RK2pdHZ6O6UqPFK0KvetcdqQE/pr9fVOPSmhHod1b0m9XamcMifU
pjXcg6rwwjwzJvU7pwA7ydMYgqueQwKVnAaVQEhPOuWRj3GrsAZKe+Jo2VzZiNr6
yZFv+S+lAgMBAAECggEBAKn/8xj4mfcxQvgrwt+b1Z6tUvk+B3orKmMNZhK8h6+f
eNMHQQqzV9TRmUhlR4PNqeEFMzk8g9Z7fT9a6Fn8FeeD/FzuBmjecj69ubO5Swb+
2sDYs/RENdDweu6xbPbE/+HYyNxcCuVpn1TIk1rBrDaZjOvvSeIDMey8EbuYK927
5Sl8D5V9Wx7gX7D76zAWNM43Li7x6O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HdvnaaFM3n1+mxqdE3dYDOc9
Ic5jDDBXgwdKWbGc3FQFOleVXdGNupIkC4G+xg3S0yyexqisGZDS/5sRIxTw2d7i
3XMYto36e0NXKSJ3q8ccgfNvFSKsQ7Gl8Kb2r+zV1dGQAB8kX3gA2djgI93t+U3C
d6WbfmFDudEcMOyvQU4kPvE7V3TR/H6VIzqZLAIyEfIklf4C5oVubs6rm+t8mcxo
zu2/B0cUs53x4h89FLTYzFSzHammxWwq8EJMTIKvMePwOubEsRXAGlTksp4lYsQZ
zXQT2y7TZw==
-----END CERTIFICATE-----
',
        // 缓存目录配置（可选，需拥有读写权限）
        'cache_path' => '',
    ];

    public function refund($orderInfo, $refundFee)
    {
        try {

            // 创建接口实例
            $wechat = new Pay($this->config);

            // 组装参数，可以参考官方商户文档
            $options = [
                'transaction_id' => $orderInfo['tradeNo'],
                'out_refund_no' => $orderInfo['orderNo'],
                'total_fee' => bcmul($orderInfo['payPrice'], 100),
                'refund_fee' => bcmul($refundFee, 100),
            ];

            // 尝试创建订单
            $result = $wechat->createRefund($options);
            if(isset($result['refund_fee'])){
                return true;
            }
        } catch (\Exception $e) {
        }
        return false;
    }


    public function queryOrder()
    {
        try {

            // 创建接口实例
            $wechat = new Pay($this->config);

            // 组装参数，可以参考官方商户文档
            $options = [
                'transaction_id' => '1008450740201411110005820873',
                // 'out_trade_no'   => '商户订单号',
            ];

            // 尝试创建订单
            $result = $wechat->queryOrder($options);

            // 订单数据处理
            var_export($result);

        } catch (Exception $e) {

            // 出错啦，处理下吧
            echo $e->getMessage() . PHP_EOL;

        }
    }

    public function callback()
    {
        try {
            // 创建接口实例
            $wechat = new Pay($this->config);
            // 尝试创建订单
            $result = $wechat->getNotify();
            // 订单数据处理
            MemberInfo::getInstance()->insert(['text' => json_encode($result)]);
            if($result['result_code'] == 'SUCCESS' && $result['return_code'] == 'SUCCESS'){
                return $result;
            }else{
                MemberInfo::getInstance()->insert(['text' => json_encode($result)]);
            }

        } catch (\Exception $e) {
            // 出错啦，处理下吧
            MemberInfo::getInstance()->insert(['text' => json_encode($e->getMessage())]);

        }
        return false;
    }


    /**
     * @param $iv
     * @param $sessionKey
     * @param $encryptedData
     * @return bool
     */
    public function appletLogin($iv, $sessionKey, $encryptedData)
    {
        $iv = $this->define_str_replace($iv);
        $encryptedData = $this->define_str_replace($encryptedData);
        $mini = new Crypt($this->config);
        try {
            return $mini->decode($iv, $sessionKey, $encryptedData);
        } catch (\Exception $e) {
            return $e->getMessage();
        }

    }

    public function define_str_replace($data)
    {
        return str_replace(' ', '+', $data);
    }


    /**
     * @param $code
     * @return array|false
     */
    public function code($code)
    {
        $mini = new Crypt($this->config);
        try {
            return $mini->session($code);
        } catch (\Exception $e) {
            return $e->getMessage();
        }

    }


    public function index($payInfo, $userInfo)
    {
        // 创建接口实例
        $wechat = new Pay($this->config);
        // 组装参数，可以参考官方商户文档
        $options = [
            'body' => '玖佰贝商品购买',
            'out_trade_no' => $payInfo['pay_no'],
            'total_fee' => $payInfo['pay_price'] * 100,
            'openid' => $userInfo['open_id'],
            'trade_type' => 'JSAPI',
            'notify_url' => 'https://jbb.qlroad.com/api/callback/wechat',
        ];

        try {
            // 生成预支付码
            $result = $wechat->createOrder($options);
            // 创建JSAPI参数签名
            return $wechat->createParamsForJsApi($result['prepay_id']);

        } catch (\Exception $e) {

            return $e->getMessage();

        }
    }
}